﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.DataAccess.Entities;
using CRM.Business.Services;
using CRM.Encryption;
using Telerik.Web.UI;
namespace Web.Contact
{
    public partial class Contacts : System.Web.UI.Page
    {
        static USER user;
        static List<CONTACT_DETAIL> contactDetails;
        static long? assignedtoID = null;
        static ROLE r;
        static List<long?> ListOrgID;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
                return;
            assignedtoID = null;
            user = (USER)Session["User"];
            if (user != null)
            {
                DateTime dt = DateTime.Now;
                DateTime dt2 = dt.AddMonths(-3);
                dpDateCreatedFrom.SelectedDate = new DateTime(dt2.Year, dt2.Month, 1);
                dpDateCreatedTo.SelectedDate = DateTime.Now;
                LoadAllUser();
                LoadEmailTemplate();
                r = RoleService.GetRoleByID((long)user.ROLE_ID);
                if ((!(bool)user.IS_ADMIN) && (!(bool)r.IS_MANAGER))
                {
                    assignedtoID = user.ID;
                    divAssignTo.Visible = false;
                    lbtnExportToCSV.Visible = false;
                }
                ListOrgID = new List<long?>();
                contactDetails = getDatasource(dpDateCreatedFrom.SelectedDate, dpDateCreatedTo.SelectedDate.Value.AddHours(24), "", "", ListOrgID, "", "", assignedtoID);
                RadGrid1.DataSource = contactDetails;
                RadGrid1.DataBind();
                
            }
        }
     
        private void LoadEmailTemplate()
        {
            ddlEmailTemplate.DataSource = EmailTemplateService.GetEmailTemplateByCondition("", "", "");
            ddlEmailTemplate.DataBind();
            ddlEmailTemplate.Items.Insert(0, new RadComboBoxItem("None", "-1"));
        }
        private void LoadAllUser()
        {
            ddlAssignedTo.Items.Clear();
            List<USER> users = UserService.ListAll();
            if (users != null)
            {
                foreach (USER u in users)
                {
                    ddlAssignedTo.Items.Add(new RadComboBoxItem(u.SUR_NAME + " " + u.NAME, u.ID.ToString()));
                }
            }
            ddlAssignedTo.Items.Insert(0, new RadComboBoxItem("Select an option", "-1"));
        }
        private List<CONTACT_DETAIL> getDatasource(DateTime? dateFrom, DateTime? dateTo, string surname, string name, List<long?> ListOrgID, string primaryemail, string officephone, long? assignid)
        {
            List<CONTACT_DETAIL> dt = ContactService.GetContactByCondition(dateFrom, dateTo, surname, name, ListOrgID, primaryemail, officephone, assignid);
            if (dt == null)
                dt = new List<CONTACT_DETAIL>();
            return dt;
        }
        protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {
            GridDataItem dataItem = e.Item as GridDataItem;
            switch (e.CommandName)
            {
                case "Edit":                    
                    Response.Redirect("EditContact.aspx?id=" + dataItem.GetDataKeyValue("CONTACT_ID").ToString());
                    break;
                case "Delete":
                    long contactID = Convert.ToInt64(dataItem.GetDataKeyValue("CONTACT_ID").ToString());
                    contactDetails.Remove(contactDetails.Where(x => x.CONTACT_ID == contactID).FirstOrDefault<CONTACT_DETAIL>());
                    int deleteContact = ContactService.DeleteContact(contactID);
                    if (deleteContact == 1)
                    {
                        RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessage('" + "Delete contact successful !" + "');");
                        //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('Delete contact successful !');", true);
                    }
                    else
                    {
                        RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessage('" + "Can not delete contact !" + "');");
                        //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('Can not delete contact !');", true);
                    }
                    break;
                default:
                    break;
            }
        }
        protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            RadGrid1.DataSource = contactDetails;
        }

        protected void btnSearch_ServerClick(object sender, EventArgs e)
        {
            if (divAssignTo.Visible)
            {
                long? at = Convert.ToInt64(ddlAssignedTo.SelectedValue);
                assignedtoID = at == -1 ? null : at;
            }

            ListOrgID = new List<long?>();
            string str1 = hdntxtOrgID.Value;
            string[] arr1 = str1.Split(';');
            foreach (string str in arr1)
            {
                if (str != "")
                {
                    ListOrgID.Add(Convert.ToInt64(str));
                }
            }
            contactDetails = getDatasource(dpDateCreatedFrom.SelectedDate, dpDateCreatedTo.SelectedDate.Value.AddHours(24), txtSurName.Text.Trim(), txtName.Text.Trim(), ListOrgID,
                txtEmail.Text.Trim(), txtPhone.Text.Trim(), assignedtoID);
            RadGrid1.DataSource = contactDetails;
            RadGrid1.DataBind();
            System.Threading.Thread.Sleep(1000);
        }

        protected void btnAddContact_ServerClick(object sender, EventArgs e)
        {
            Response.Redirect("AddNewContact.aspx");
        }
        
        protected void sendEmail_Click(object sender, EventArgs e)
        {
            LinkButton lbtnSendEmail = sender as LinkButton;
            EMAIL_TEMPLATE email = new EMAIL_TEMPLATE();
            email.SUBJECT = " ";
            email.MESSAGE = " ";
            EMAIL_TEMPLATE emailTemplate = EmailTemplateService.GetEmailTemplateByID(Convert.ToInt64(ddlEmailTemplate.SelectedValue.ToString()));
            if (emailTemplate != null)
            {
                email = emailTemplate;

            }
            string mailto = lbtnSendEmail.Text;
            string t = "parent.location='mailto:" + mailto + "?Subject=" + email.SUBJECT + "&Body=" + email.MESSAGE + "'";
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", t, true);
        }
        private void LoadAllUser(RadComboBox ddlAssignedTo)
        {
            ddlAssignedTo.Items.Clear();
            List<USER> users = UserService.ListAll();
            if (users != null)
            {
                foreach (USER u in users)
                {
                    ddlAssignedTo.Items.Add(new RadComboBoxItem(u.SUR_NAME + " " + u.NAME, u.ID.ToString()));
                }
            }
        }
        protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridPagerItem)
            {
                GridPagerItem oGridPagerItem = (GridPagerItem)e.Item;
                RadComboBox oRadComboBox = (RadComboBox)oGridPagerItem.FindControl("PageSizeComboBox");
                oRadComboBox.Width = Unit.Pixel(50);
            }
        }

        protected void RadGrid1_PreRender(object sender, EventArgs e)
        {
            
            if ((!(bool)user.IS_ADMIN) && (!(bool)r.IS_MANAGER))
            {
                RadGrid1.MasterTableView.GetColumn("ASSIGN_TO").Visible = false;
                RadGrid1.MasterTableView.GetColumn("SUR_NAME").ItemStyle.Width = Unit.Percentage(20);
                RadGrid1.MasterTableView.GetColumn("SUR_NAME").HeaderStyle.Width = Unit.Percentage(20);
                RadGrid1.MasterTableView.GetColumn("NAME").ItemStyle.Width = Unit.Percentage(20);
                RadGrid1.MasterTableView.GetColumn("NAME").HeaderStyle.Width = Unit.Percentage(20);
            }
            foreach (GridGroupHeaderItem groupHeader in RadGrid1.MasterTableView.GetItems(GridItemType.GroupHeader))
            {
                GridDataItem item = groupHeader.GetChildItems()[0] as GridDataItem;
                object key = item.GetDataKeyValue("OrgID");
                string strtxt = groupHeader.DataCell.Text;

                Label lbl = new Label();
                lbl.ID = "lblGroupHeader";
                lbl.Text = (key == null ? "NULL" : strtxt.Replace("ORGANIZATION_NAME: ", ""));
                lbl.ForeColor = System.Drawing.Color.Blue;
                groupHeader.DataCell.Controls.Clear();
                groupHeader.DataCell.Controls.Add(lbl);
            }  
        }
        protected void lbtnExportToCSV_ServerClick(object sender, EventArgs e)
        {
            RadGrid1.ExportSettings.IgnorePaging = true;
            RadGrid1.ExportSettings.OpenInNewWindow = true;
            RadGrid1.ExportSettings.UseItemStyles = true;
            DateTime dt = DateTime.Now;
            RadGrid1.ExportSettings.FileName = "Contacts_" + dt.Year + dt.Month + dt.Day;
            RadGrid1.MasterTableView.GetColumn("TOOLS").Display = false;
            RadGrid1.MasterTableView.ExportToCSV();
        }
        protected void lbtnImport_ServerClick(object sender, EventArgs e)
        {
            Response.Redirect("ImportFromExcelFile.aspx");
        }
        
    }
}